<!--
 * @Description: 
 * @Author: charles
 * @Date: 2021-11-10 14:11:48
 * @LastEditors: charles
 * @LastEditTime: 2021-11-10 15:00:21
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>组件通信-上下文</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/react/17.0.2/umd/react.development.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.2/umd/react-dom.development.min.js"></script>
  <script src="https://cdn.bootcss.com/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
  <div id="app"></div>
  <script type="text/babel">
    // 根
    const BaseContext = React.createContext();
    class App extends React.Component {
      constructor(props){
        super(props);
        this.state = {
          user:{
            id:1,
            username:"terry",
            avatar:"http://182.23.12.2:8888/sfeawfaw.png"
          }
        }
      }
      componentDidMount(){
        setInterval(() => {
          this.setState({
            user:{
              ...this.state.user,
              id:this.state.user.id + 1
            }
          })
        }, 1000);
      }
      render(){
        return (
          <BaseContext.Provider value={this.state.user}>
            <div>
              <h2>组件通信</h2>  
              <List user={this.state.user}/>
            </div>
          </BaseContext.Provider>
        )
      }
    }
    // 子
    function List(props){
      return (
        <div>
          <h3>列表</h3>
          <div>子：{props.user.username}</div>
          <div>
            <Info/>
            <Alert/>
          </div>
        </div>
      )
    }
    // 孙1
    class Info extends React.Component{
      // 1. 注册上下文（订阅）
      static contextType = BaseContext
      render(){
        return (
          <div>
            <div>信息</div>
            {
              // 2. 通过this.context访问上下文数据
            }
            <div>info: {JSON.stringify(this.context)}</div>
          </div>
        )
      }
    }
    // 孙2
    const {useContext} = React;
    function Alert(props){
      // 通过hook进行注册
      const context = useContext(BaseContext);
      return (
        <div>
          <div>弹框</div>  
          <div>alert: {JSON.stringify(context)}</div>
        </div>
      )
    }
    ReactDOM.render(<App/>,document.getElementById('app'));
  </script>
</body>
</html>
